package m2;

import com.rabbitmq.client.*;

import java.io.IOException;


public class Consumer {
    public static void main(String[] args) throws Exception {
        //连接
        ConnectionFactory f=new ConnectionFactory();
        f.setHost("192.168.64.140");
        f.setUsername("admin");
        f.setPassword("admin");
        Channel c=f.newConnection().createChannel();
        //定义队列
        c.queueDeclare("task_queue", true, false, false, null);
        DeliverCallback deliverCallback=new DeliverCallback() {
            @Override
            public void handle(String consumerTag, Delivery message) throws IOException {
                //遍历消息字符串，每个字符都暂停一秒
                String msg=new String(message.getBody());
                System.out.println("收到："+msg);
                for (int i = 0; i <msg.length() ; i++) {
                    if ('.'==msg.charAt(i)){
                        try {
                            Thread.sleep(1000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
                //发送回执
                c.basicAck(message.getEnvelope().getDeliveryTag(), false);
                System.out.println("消息处理结束11");
            }
        };
        CancelCallback cancelCallback=new CancelCallback() {
            @Override
            public void handle(String consumerTag) throws IOException {

            }
        };
        //每次只接收处理1条消息，处理完成之前不接收下一条
        //只有手动开启ACK模式才有效
        c.basicQos(1);
        //autoAck设置为false,则需要手动确认发送回执
        c.basicConsume("task_queue", false, deliverCallback, cancelCallback);
    }
}
